package com.iwhalecloud.bss.kite.cucc.web.controller.account;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.cart.client.dto.req.payrelation.KiteCartAccountReqDTO;
import com.iwhalecloud.bss.kite.cart.client.dto.rsp.payrelation.KiteCartAccountRspDTO;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.*;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.TargetAccountInfoVO;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.svcability.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.cust.ContextCustDTO;
import com.iwhalecloud.bss.kite.client.dto.rule.common.DataRuleResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.rule.check.ICheckService;
import com.iwhalecloud.bss.kite.cucc.client.api.account.ILocalAccountService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.api.rule.check.ICuccCheckService;
import com.iwhalecloud.bss.kite.cucc.client.dto.account.CustAccountDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.account.QryCustAccountReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.order.KiteOfferInstAcctVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.UnicomRegionCache;
import com.iwhalecloud.bss.kite.cucc.manager.inst.CuccKiteOfferInstAcct;
import com.iwhalecloud.bss.kite.cucc.manager.inst.KiteCuccOfferInstAcct;
import com.iwhalecloud.bss.kite.cucc.manager.scene.service.operate.LocalOperateOfferInstAcctRelService;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.service.inst.ProdInstService;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.enums.RelType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstAcct;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.inst.change.KiteInstChange;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.util.RuleParamUtils;
import com.iwhalecloud.bss.pub.client.constanst.Symbols;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.rul.core.client.dto.common.RuleCommonParam;
import com.ztesoft.bss.rul.core.client.dto.kite.KiteRuleResponse;
import com.ztesoft.bss.svcability.util.ListUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(tags = {"/cuccAccount - 账户"})
@RestController("cuccAccount")
@RequestMapping("/cuccAccount")
public class AccountController {

    @Autowired
    private ILocalAccountService accountService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private LocalOperateOfferInstAcctRelService operateOfferInstAcctRelService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private ICheckService checkService;


    @Autowired
    private ICuccCheckService cuccCheckService;

    @Autowired
    private ICustReceptionService custReceptionService;

    @Autowired
    private IOrderService orderService;

    @KiteTransactional
    @ApiOperation(value = "添加账户", notes = "添加账户")
    @PostMapping("addAccount")
    @ApiImplicitParams({@ApiImplicitParam(name = "payName", value = "账户名称", required = true),
        @ApiImplicitParam(name = "accountType", value = "账户类型", required = true),
        @ApiImplicitParam(name = "accountCycle", value = "财务周期", required = false),
        @ApiImplicitParam(name = "payCycle", value = "付费周期", required = false),
        @ApiImplicitParam(name = "linkName", value = "联系人姓名", required = false),
        @ApiImplicitParam(name = "linkPhone", value = "联系人电话", required = false),
        @ApiImplicitParam(name = "linkEmail", value = "联系人Email", required = false),
        @ApiImplicitParam(name = "linkAddress", value = "联系人地址", required = false),
        @ApiImplicitParam(name = "postBill", value = "是否寄送账单", required = false),
        @ApiImplicitParam(name = "isCenterDirectSign", value = "是否总部直签", required = false),
        @ApiImplicitParam(name = "billType", value = "邮寄方式", required = false),
        @ApiImplicitParam(name = "billCycle", value = "邮寄周期", required = false),
        @ApiImplicitParam(name = "billContent", value = "邮寄内容", required = false),
        @ApiImplicitParam(name = "billEmail", value = "Email邮箱", required = false),
        @ApiImplicitParam(name = "faxNumber", value = "传真号码", required = false),
        @ApiImplicitParam(name = "recipientName", value = "收件人姓名", required = false),
        @ApiImplicitParam(name = "billAddress", value = "邮寄地址", required = false),
        @ApiImplicitParam(name = "postcode", value = "邮政编码", required = false),
        @ApiImplicitParam(name = "remark", value = "备注", required = false),
        @ApiImplicitParam(name = "bankAcctName", value = "开户名称", required = false),
        @ApiImplicitParam(name = "bankAcctNo", value = "银行账号", required = false),
        @ApiImplicitParam(name = "bankCode", value = "开户银行", required = false),
        @ApiImplicitParam(name = "superBankCode", value = "所属银行", required = false),
        @ApiImplicitParam(name = "limitMode", value = "托收方式", required = false),
        @ApiImplicitParam(name = "limitMoney", value = "托收金额", required = false),
        @ApiImplicitParam(name = "agreementNo", value = "托收协议号", required = false),
        @ApiImplicitParam(name = "fdContactName", value = "财务联系人姓名", required = false),
        @ApiImplicitParam(name = "fdContactPhone", value = "财务联系人电话", required = false),
        @ApiImplicitParam(name = "newCustId", value = "过户目标客户custId", required = false),
        @ApiImplicitParam(name = "state", value = "账户状态", required = false),
        @ApiImplicitParam(name = "fdContactEmail", value = "财务联系人邮箱", required = false),
        @ApiImplicitParam(name = "currency", value = "币种", required = false),
        @ApiImplicitParam(name = "postLang", value = "账单邮寄语种", required = false),
        @ApiImplicitParam(name = "accDetailType", value = "是否需要明细账单", required = false)
    })
    public DataResult<Map<String, Object>> addAccount(@RequestParam(required = true) String payName,
        @RequestParam(required = true) String accountType, @RequestParam(required = false) String accountCycle,
        @RequestParam(required = false) String payCycle, @RequestParam(required = false) String linkName,
        @RequestParam(required = false) String linkPhone, @RequestParam(required = false) String linkEmail,
        @RequestParam(required = false) String linkAddress, @RequestParam(required = false) String postBill,
        @RequestParam(required = false) String isCenterDirectSign, @RequestParam(required = false) String billType,
        @RequestParam(required = false) String billCycle, @RequestParam(required = false) String billContent,
        @RequestParam(required = false) String billEmail, @RequestParam(required = false) String faxNumber,
        @RequestParam(required = false) String recipientName, @RequestParam(required = false) String billAddress,
        @RequestParam(required = false) String postcode, @RequestParam(required = false) String remark,
        @RequestParam(required = false) String bankAcctName, @RequestParam(required = false) String bankAcctNo,
        @RequestParam(required = false) String bankCode, @RequestParam(required = false) String superBankCode,
        @RequestParam(required = false) String limitMode, @RequestParam(required = false) String limitMoney,
        @RequestParam(required = false) String agreementNo, @RequestParam(required = false) String fdContactName,
        @RequestParam(required = false) String fdContactPhone, @RequestParam(required = false) String newCustId,
        @RequestParam(required = false) String state, @RequestParam(required = false) String fdContactEmail,
        @RequestParam(required = false) String currency, @RequestParam(required = false) String postLang,
        @RequestParam(required = false) String accDetailType) {
        CuccContextCustDTO custDTO = new CuccContextCustDTO();
        if (KiteStringUtils.isNotEmpty(newCustId)) {
            CuccCustInfoDetailDTO cuccCustInfoDTO = custReceptionService.getCustomerInfoNew(newCustId);
            if (Objects.nonNull(cuccCustInfoDTO)) {
                KiteBeanUtils.copyProperties(cuccCustInfoDTO, custDTO);
                custDTO.setCustId(cuccCustInfoDTO.getCustId());
                custDTO.setCustName(cuccCustInfoDTO.getCustName());
                custDTO.setGroupId(cuccCustInfoDTO.getGroupId());
                // custDto获取不到时取登录信息省份地市信息
                if (KiteStringUtils.isEmpty(cuccCustInfoDTO.getProvinceCode())) {
                    custDTO.setProvinceCode(ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
                } else {
                    custDTO.setProvinceCode(cuccCustInfoDTO.getProvinceCode());
                }
                if (KiteStringUtils.isEmpty(cuccCustInfoDTO.getEparchyCode())) {
                    custDTO.setEparchyCode(ContextUtil.getLoginInfo().getUserInfo().getPostLanId());
                } else {
                    custDTO.setEparchyCode(cuccCustInfoDTO.getEparchyCode());
                }
            }
        } else {
            ContextCustDTO conCustDTO = KiteWebContext.getContext().getCust();
            custDTO = KiteBeanUtils.transform(conCustDTO, CuccContextCustDTO.class);
        }

        String orgProvinceCode=ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if(!KiteStringUtils.isEmpty(orgProvinceCode)&&orgProvinceCode.startsWith("49")){
            //国际账户添加用同步接口，云业务
            return ErrorConsts.SUCCESS.getResult(accountService
                .sysncNationAccount(custDTO, payName, accountType, accountCycle, payCycle, linkName, linkPhone, linkEmail,
                    linkAddress, postBill, isCenterDirectSign, billType, billCycle, billContent, billEmail, faxNumber,
                    recipientName, billAddress, postcode, remark, bankAcctName, bankAcctNo, bankCode, superBankCode,
                    limitMode, limitMoney, agreementNo, fdContactName, fdContactPhone,state,fdContactEmail,currency,postLang,accDetailType));
        }else {
            return ErrorConsts.SUCCESS.getResult(accountService
                .addAccount(custDTO, payName, accountType, accountCycle, payCycle, linkName, linkPhone, linkEmail,
                    linkAddress, postBill, isCenterDirectSign, billType, billCycle, billContent, billEmail, faxNumber,
                    recipientName, billAddress, postcode, remark, bankAcctName, bankAcctNo, bankCode, superBankCode,
                    limitMode, limitMoney, agreementNo, fdContactName, fdContactPhone));
        }


    }

//    @ApiOperation(value = "国际账户同步")
//    @PostMapping("/createAccountForNational")
//    public DataResult<KiteCartAccountRspDTO> createAccount(@RequestBody KiteCartAccountReqDTO accountReqDTO) {
//        return ErrorConsts.SUCCESS.getResult(accountService.sysncNationAccount(accountReqDTO));
//    }
    @ApiOperation(value = "分页查询账户列表", notes = "分页查询账户列表")
    @GetMapping("/custAccountInfos")
    @ApiImplicitParams({@ApiImplicitParam(name = "custId", value = "客户编码", required = false),
        @ApiImplicitParam(name = "payName", value = "账户名", required = false),
        @ApiImplicitParam(name = "acountType", value = "账户类型", required = false),
        @ApiImplicitParam(name = "acctId", value = "账户编码", required = false),
        @ApiImplicitParam(name = "cbssAcountCode", value = "cBSS账户编码", required = false),
        @ApiImplicitParam(name = "provinceAcctId", value = "省份账户编码", required = false),
        @ApiImplicitParam(name = "payCompactNo", value = "付费合同", required = false),
        @ApiImplicitParam(name = "provinceCode", value = "归属省份", required = false),
        @ApiImplicitParam(name = "eparchyCode", value = "归属地市", required = false),
        @ApiImplicitParam(name = "pageNum", value = "第几页", required = false),
        @ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false),
        @ApiImplicitParam(name = "custName", value = "客户名称", required = false),
        @ApiImplicitParam(name = "accNum", value = "业务号码", required = false),
        @ApiImplicitParam(name = "modifyAccount", value = "修改账户标识", required = false)
    })
    public DataResult<PageInfo<Map>> pageCustAccountInfo(@RequestParam(required = false) String custId,
        @RequestParam(required = false) String payName, @RequestParam(required = false) String acountType,
        @RequestParam(required = false) String acctId, @RequestParam(required = false) String cbssAcountCode,
        @RequestParam(required = false) String provinceAcctId, @RequestParam(required = false) String payCompactNo,
        @RequestParam(required = false) String provinceCode, @RequestParam(required = false) String eparchyCode,
        @RequestParam(required = true) int pageNum, @RequestParam(required = true) int pageSize,
        @RequestParam(required = false) String custName, @RequestParam(required = false) String accNum,
        @RequestParam(required = false) String modifyAccount) {

        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        if (KiteStringUtils.equals("T", modifyAccount)) {
            if (KiteStringUtils.isEmpty(provinceCode)) {
                provinceCode = loginInfo.getUserInfo().getPostProvinceNbr();
            }
            if (KiteStringUtils.isEmpty(eparchyCode)) {
                eparchyCode = loginInfo.getUserInfo().getPostLanId();
            }
        } else {
            CuccContextCustDTO cuccContextCustDTO = (CuccContextCustDTO) KiteWebContext.getContext().getCust();
            if (KiteStringUtils.isEmpty(provinceCode)) {
                provinceCode = cuccContextCustDTO.getProvinceCode();
            }
            if (KiteStringUtils.isEmpty(eparchyCode)) {
                eparchyCode = cuccContextCustDTO.getEparchyCode();
            }
        }
        if (KiteStringUtils.isNotBlank(accNum) && KiteStringUtils.isBlank(custId)) {
            String staffCode = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");
            Map<String, Object> userInfoMap = SpringUtil.getBean(ProdInstService.class)
                .queryCustIdByAccNum(accNum, staffCode, provinceCode, eparchyCode);
             String custIdByAccNum = KiteMapUtils.getString(userInfoMap, "CUST_ID");
            if (KiteStringUtils.isNotBlank(custIdByAccNum) && (KiteStringUtils.isBlank(custId) || KiteStringUtils
                .equals(custId, custIdByAccNum))) {
                custId = custIdByAccNum;
            }
            else {
                return ErrorConsts.SUCCESS.getResult(new PageInfo<>());
            }
        }
        // 获取是否总部收费属性
        KiteAttr isChargeAttr = querySceneInstService.getCommonAttrsByFieldName(KiteWebContext.getContext().getCurrentSceneInstId(), LocalKeyConsts.IS_LEADER_CHARGE, LocalKeyConsts.GROUPUSERINFO_MODULEID);
        if (Objects.isNull(isChargeAttr)) {
            isChargeAttr = querySceneInstService.getCommonAttrsByFieldName(KiteWebContext.getContext().getCurrentSceneInstId(), LocalKeyConsts.IS_LEADER_CHARGE_NEW, LocalKeyConsts.GROUPUSERINFO_MODULEID);
        }
        PageInfo<QryCustAccountReq> list;
        PageInfo<Map> result = new PageInfo<>();
        if (Objects.nonNull(isChargeAttr) && ("1".equals(isChargeAttr.getValue()) || "1_0000106".equals(isChargeAttr.getValue()))) {
           if(KiteStringUtils.isNotEmpty(provinceCode)&&!provinceCode.startsWith("49")){
                list = accountService.listCustAccountInfoBySign(custId, payName, acountType, acctId, cbssAcountCode, provinceAcctId, payCompactNo,
                    provinceCode, eparchyCode, null, "1", pageNum, pageSize);
            }else {
                list = accountService.listCustAccountInfo(custId, payName, acountType, acctId, cbssAcountCode, provinceAcctId, payCompactNo,
                    provinceCode, eparchyCode, null, pageNum, pageSize);
            }
        } else {
            list = accountService.listCustAccountInfo(custId, payName, acountType, acctId, cbssAcountCode, provinceAcctId, payCompactNo,
                provinceCode, eparchyCode, null, pageNum, pageSize);
        }
        KiteBeanUtils.copyProperties(list, result, "list");
        result.setList(new ArrayList<>());

        list.getList().stream().forEach(account -> {
            if (Objects.nonNull(account.getCustAccount().getOpenDate())) {
                Long time = account.getCustAccount().getOpenDate().getTime();
                account.getCustAccount().setOpenDateFormat(DateUtils.formatTime(time));
            }
            String provinceName = LocalAttrHelper.getRegionName(account.getCustAccount().getProvinceCode());
            String eparchyName = LocalAttrHelper.getRegionName(account.getCustAccount().getEparchyCode());
            account.getCustAccount()
                .setAccountLocation(KiteStringUtils.join(provinceName, Symbols.HYPHEN, eparchyName));
            //临时处理查询账户因返回Long类型到前端丢失精度的问题
            Map<Object, Object> accountMap = KiteMapUtils.beanToMap(account);
            CustAccountDTO custAccount = (CustAccountDTO) accountMap.get("custAccount");
            Map<Object, Object> custAccountMap = KiteMapUtils.beanToMap(custAccount);
            custAccountMap.put("custId",Long.toString(custAccount.getCustId()));
            custAccountMap.put("acctId",Long.toString(custAccount.getAcctId()));
            accountMap.put("custAccount", custAccountMap);
            /**
             * 改为使用服务端时间
             * add by ma.junjun  2021-08-27
             * 天梯 id  ：9700   0909版本大数据设置付费关系bug修复  ：存在修改客户端时间的情况，造成时间不准。
             */

            //开始时间
            accountMap.put("startDate", DateUtils.getMonthString());
            //截止时间
            accountMap.put("endDate", "2099-12");
            result.getList().add(accountMap);
        });

        //        if(!KiteStringUtils.isEmpty(accountName)){
        //            Iterator iterator = list.iterator();
        //            while (iterator.hasNext()) {
        //                JSONObject next = (JSONObject) iterator.next();
        //                Map<String, String> map = (Map) next.get("custAccount");
        //                if (!KiteStringUtils.isEqual(accountName, Const.getStrValue(map, "payName"))) {
        //                    iterator.remove();
        //                }
        //            }
        //        }

        return ErrorConsts.SUCCESS.getResult(result);
    }

    @KiteTransactional
    @ApiOperation(value = "增加账户实例", notes = "增加账户实例")
    @PostMapping("addOfferInstAcctRels")
    @ApiImplicitParams({@ApiImplicitParam(name = "acctRels", value = "关联账户（付费关系）", required = true)})
    public DataResult<Map<String, String>> addOfferInstAcctRels(
        @RequestBody(required = true) List<CuccKiteOfferInstAcct> acctRels) {
        DataResult<Map<String, String>> param = new DataResult<Map<String, String>>();

        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        String custId = KiteWebContext.getContext().getCustId();
        List<KiteOfferInstAcct> delOfferInstAccts = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.OFFER_INST_ACCT));

        String allFlag = DcPublicCache.getCodea("2019061408", "rule_all_close_flag");
        if ("F".equals(allFlag)) {
            for (CuccKiteOfferInstAcct offerInstAcct : acctRels) {
                String offerInstId = offerInstAcct.getOfferInstId();
                String result = operateSceneInstService.checkAddingOfferInstAcct(custId, offerInstId, acctRels);
                if (!KiteObjectUtils.isEmpty(result)) {
                    BssException.throwOut("", "", result);
                }
            }
        } else {
            RuleCommonParam ruleCommonParam = RuleParamUtils.getRuleParam();
            Map map = new HashMap();
            List acctRelList = new ArrayList();
            acctRels.stream().forEach(acctRel -> {
                Map acctRelMap = KiteMapUtils.beanToMap(acctRel);
                acctRelList.add(acctRelMap);
            });
            map.put("prodInstAcctRels", acctRelList);
            ruleCommonParam.setParams(map);
            KiteRuleResponse response = checkService
                .onAddProdInstAcctRule(sceneInstId, "", "", "", ruleCommonParam);
            DataRuleResult dataRuleResult = RuleResponseUtils.cheackRuleResp(response);
        }
        for (CuccKiteOfferInstAcct offerInstAcct : acctRels) {
            if (KiteStringUtils.equals(offerInstAcct.getActionType().name(), ActionType.D.name())) {
                operateSceneInstService.deleteOfferInstAcct(sceneInstId, offerInstAcct.getOfferObjInstRelId());
            } else {
                String offerInstId = offerInstAcct.getOfferInstId();
                offerInstAcct.setInstType(InstType.OFFER_INST_ACCT);
                KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, offerInstId);
                if (KiteObjectUtils.isEmpty(offerInst)) {
                    ErrorConsts.OFFER_INST_NOT_EXIST.throwOut(offerInstId, custId);
                }
                // 没有账户明细关系，明细ID传销售品id
                String offerId = Optional.ofNullable(OfferCache.get(offerInst.getOfferId())).map(Offer::getOfferId)
                    .orElse("");
                operateSceneInstService
                    .addOfferInstAcct(sceneInstId, offerInstAcct, offerInstId, RelType.OFFER_OBJ_REL_TYPE_170000,
                        ActionType.A, KeyConsts.OFFER_ACCOUNT_ROLE, offerId);
            }

            //原默认账户变成非默认账户，开始账期不能是当月以及当月之前
            String result = operateOfferInstAcctRelService.checkAddingOfferInstAcct(offerInstAcct, delOfferInstAccts);
            if (!KiteObjectUtils.isEmpty(result)) {
                BssException.throwOut("", "", result);
            }
        }

        param.setResultCode("0");
        param.setResultMsg("SUCCESS");
        return param;
    }

    @ApiOperation(value = "查询账户实例", notes = "查账户实例")
    @GetMapping("listOfferInstAcctRels")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例ID", required = false),
        @ApiImplicitParam(name = "offerInstId", value = "销售品实例ID", required = false)
    })
    public DataResult<List<KiteOfferInstAcctVO>> listOfferInstAcctRels(
        @RequestParam(required = false) String sceneInstId, @RequestParam(required = false) String offerInstId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        List<CuccKiteOfferInstAcct> offerInstAccts = Lists.newArrayList();
        KiteSceneInst inst =querySceneInstService.getSceneInst(sceneInstId);
        KiteOfferInst mainOfferInst =querySceneInstService.getOfferInst(inst.getCustId(),inst.getRootInstId());
//        KiteOfferInst giftOfferInst =querySceneInstService.getOfferInst(inst.getCustId(),inst.getRootInstId());
        List<KiteOfferInst> giftOfferInsts = querySceneInstService.listGiftOfferInsts(sceneInstId);
//        List<KiteOfferInst> mainOfferInsts = this.querySceneInstService.listMainOfferInsts(sceneInstId);
        if (KiteListUtils.isNotEmpty(giftOfferInsts)) {
            KiteOfferInst offerInst = giftOfferInsts.get(0);
            List<CuccKiteOfferInstAcct> cuccKiteOfferInstAccts = KiteBeanUtils.copyPropsForList(operateOfferInstAcctRelService
                .listOfferInstAccts(KiteWebContext.getContext().getCustId(), offerInst.getOfferInstId()), CuccKiteOfferInstAcct.class);
            cuccKiteOfferInstAccts.stream()
                .filter(cuccKiteOfferInstAcct -> KiteStringUtils.isEmpty(cuccKiteOfferInstAcct.getOfferName()))
                .forEach(cuccKiteOfferInstAcct -> {
                    cuccKiteOfferInstAcct.setOfferName(offerInst.getOfferName());
                });
            offerInstAccts.addAll(cuccKiteOfferInstAccts);
        }
        else {
            if (null!=mainOfferInst) {
//                for (KiteOfferInst offerInst : mainOfferInsts) {
                    List<CuccKiteOfferInstAcct> cuccKiteOfferInstAccts = KiteBeanUtils.copyPropsForList(operateOfferInstAcctRelService
                        .listOfferInstAccts(KiteWebContext.getContext().getCustId(), mainOfferInst.getOfferInstId()), CuccKiteOfferInstAcct.class);
                    cuccKiteOfferInstAccts.stream()
                        .filter(cuccKiteOfferInstAcct -> KiteStringUtils.isEmpty(cuccKiteOfferInstAcct.getOfferName()))
                            .forEach(cuccKiteOfferInstAcct -> {
                                cuccKiteOfferInstAcct.setOfferName(mainOfferInst.getOfferName());
                            });
                    offerInstAccts.addAll(cuccKiteOfferInstAccts);
//                }
            }
        }
        List<CuccKiteOfferInstAcct> OfferInstAcctDelete=querySceneInstService.listInsts(sceneInstId, edu.emory.mathcs.backport.java.util.Collections.singletonList(InstType.OFFER_INST_ACCT));
        if(KiteListUtils.isNotEmpty(OfferInstAcctDelete)){
            OfferInstAcctDelete= KiteBeanUtils.copyPropsForList(OfferInstAcctDelete, CuccKiteOfferInstAcct.class).stream()
                .filter(s->{
                    s.setOfferInstId(mainOfferInst.getInstId());
                    return "D".equals(s.getActionType().name());
                }).collect(Collectors.toList());
            if(KiteListUtils.isNotEmpty(OfferInstAcctDelete)){
                offerInstAccts.addAll(KiteBeanUtils.copyPropsForList(OfferInstAcctDelete, CuccKiteOfferInstAcct.class));
            }
        }

        List<KiteOfferInstAcctVO> copy = KiteBeanUtils.copyPropsForList(offerInstAccts, KiteOfferInstAcctVO.class);
        List<KiteOfferInstAcctVO> copys= Lists.newArrayList();
        if (KiteListUtils.isNotEmpty(copy)) {
            KiteAttr accNumAttr = querySceneInstService.getCommonAttr(sceneInstId, "business_number");
            String accNum = accNumAttr != null ? accNumAttr.getValue() : "";

            for (KiteOfferInstAcctVO vo : copy) {
                if (vo == null||"X".equals(vo.getActionType().name())) {
                    continue;
                }
                String cbssAccountCode = vo.getCbssAccountCode();

                if(!KiteStringUtils.isNotBlank(cbssAccountCode)){
                    CuccContextCustDTO cuccContextCustDTO = (CuccContextCustDTO) KiteWebContext.getContext().getCust();
                    String provinceCode = cuccContextCustDTO.getProvinceCode();
                    String eparchyCode = cuccContextCustDTO.getEparchyCode();
                    PageInfo<QryCustAccountReq> list = accountService
                        .listCustAccountInfo(KiteWebContext.getContext().getCustId(), "", "", vo.getAcctId(), "", "", "", provinceCode,
                            eparchyCode,null, 1, 5);
                    List<QryCustAccountReq> infResult = list.getList();
                    if (KiteListUtils.isNotEmpty(infResult)) {
                        QryCustAccountReq req = infResult.get(0);
                        final CustAccountDTO custAccount = req.getCustAccount();
                        cbssAccountCode =  custAccount.getCbssAccountCode();
                        vo.setContractId(custAccount.getContractId());
                        vo.setCustName(custAccount.getCustName());
                    }
                    vo.setCbssAccountCode(cbssAccountCode);
                }

                vo.setAccNum(accNum);
                if("D".equals(vo.getActionType().name())){
                    vo.setEndDate(KiteDateUtils.formatDate("yyyy-MM"));
                    vo.setCycleType("D");
                };
                copys.add(vo);
            }
        }

        return ErrorConsts.SUCCESS.getResult(copys);
    }

    @KiteTransactional
    @ApiOperation(value = "删除账户实例", notes = "删除账户实例")
    @DeleteMapping
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "sceneInstId", required = true),
        @ApiImplicitParam(name = "offerInstId", value = "offerInstId", required = true),
        @ApiImplicitParam(name = "offerInstAcctRelId", value = "offerInstAcctRelId", required = true)
    })
    public DataResult<Boolean> deleteOfferInstAcctRel(@RequestParam(required = true) String sceneInstId,
        @RequestParam(required = true) String offerInstId, @RequestParam(required = true) String offerInstAcctRelId) {

        /**
         * 付费关系-删除规则埋点-start
         */
        String custId = querySceneInstService.getSceneInst(sceneInstId).getCustId();
        KiteOfferInstAcct delOfferInstAcct = querySceneInstService.getOfferInstAcct(custId, offerInstAcctRelId);
        RuleCommonParam ruleCommonParam = RuleParamUtils.getRuleParam(custId);
        cuccCheckService.onDelOfferInstAcctCheck(sceneInstId, ruleCommonParam, delOfferInstAcct);
        /**
         * 付费关系-删除规则埋点-end
         */

        return ErrorConsts.SUCCESS
            .getResult(operateSceneInstService.deleteOfferInstAcct(sceneInstId, offerInstAcctRelId));
    }

    @KiteTransactional
    @ApiOperation(value = "当前登录人地区", notes = "当前登录人地区")
    @GetMapping("/queryLoginInfoAreaName")
    public DataResult<Map<String, Object>> queryAreaNameByCode() {
        String lanId = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        //        String areaName = queryDevInfoService.queryAreaNameByCode("", lanId);
        UnicomRegion unicomRegion = UnicomRegionCache.getOneUnicomRegion(lanId);
        String areaName = lanId;
        if (Objects.nonNull(unicomRegion)) {
            areaName = unicomRegion.getRegionName();
        }
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        Map<String, Object> param = new HashMap<>();
        param.put("areaName", areaName);
        param.put("areaCode", lanId);
        param.put("provinceCode", provinceCode);
        return ErrorConsts.SUCCESS.getResult(param);
    }

    @KiteTransactional
    @ApiOperation(value = "修改账户信息",notes = "修改账户信息")
    @PostMapping("modCustAccount")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "acctId", value = "账户编码", required = true),
        @ApiImplicitParam(name = "payName", value = "账户名称", required = true),
        @ApiImplicitParam(name = "accountType", value = "账户类型", required = true),
        @ApiImplicitParam(name = "accountCycle", value = "财务周期", required = false),
        @ApiImplicitParam(name = "payCycle", value = "付费周期", required = false),
        @ApiImplicitParam(name = "linkName", value = "联系人姓名", required = false),
        @ApiImplicitParam(name = "linkPhone", value = "联系人电话", required = false),
        @ApiImplicitParam(name = "linkEmail", value = "联系人Email", required = false),
        @ApiImplicitParam(name = "linkAddress", value = "联系人地址", required = false),
        @ApiImplicitParam(name = "postBill", value = "是否寄送账单", required = false),
        @ApiImplicitParam(name = "isCenterDirectSign", value = "是否总部直签", required = false),
        @ApiImplicitParam(name = "billType", value = "邮寄方式", required = false),
        @ApiImplicitParam(name = "billCycle", value = "邮寄周期", required = false),
        @ApiImplicitParam(name = "billContent", value = "邮寄内容", required = false),
        @ApiImplicitParam(name = "billEmail", value = "Email邮箱", required = false),
        @ApiImplicitParam(name = "faxNumber", value = "传真号码", required = false),
        @ApiImplicitParam(name = "recipientName", value = "收件人姓名", required = false),
        @ApiImplicitParam(name = "billAddress", value = "邮寄地址", required = false),
        @ApiImplicitParam(name = "postCode", value = "邮政编码", required = false),
        @ApiImplicitParam(name = "remark", value = "备注", required = false),
        @ApiImplicitParam(name = "custId", value = "客户主键标识", required = false),
        @ApiImplicitParam(name = "groupId", value = "客户编码", required = false),
        @ApiImplicitParam(name = "provinceCode", value = "省份编码", required = false),
        @ApiImplicitParam(name = "eparchyCode", value = "地市编码", required = false),
        @ApiImplicitParam(name = "bankAcctName", value = "开户名称", required = false),
        @ApiImplicitParam(name = "bankCode", value = "开户银行", required = false),
        @ApiImplicitParam(name = "superBnakCode", value = "所属银行", required = false),
        @ApiImplicitParam(name = "limitMode", value = "托收方式", required = false),
        @ApiImplicitParam(name = "agreementNo", value = "托收协议号", required = false),
        @ApiImplicitParam(name = "fdContactName", value = "财务联系人姓名", required = false),
        @ApiImplicitParam(name = "fdContactPhone", value = "财务联系人电话", required = false)
    })
    public DataResult<Map<String,Object>> modCustAccount(
        @RequestParam(required = true) String payName,@RequestParam(required = true) String accountType,
        @RequestParam(required =false) String accountCycle,@RequestParam(required = false) String payCycle,
        @RequestParam(required = false) String linkName,@RequestParam(required = false) String linkPhone,
        @RequestParam(required = false) String linkEmail,@RequestParam(required = false) String linkAddress,
        @RequestParam(required = false) String postBill,@RequestParam(required = false) String isCenterDirectSign,
        @RequestParam(required = false) String billType,@RequestParam(required = false) String billCycle,
        @RequestParam(required = false) String billContent,@RequestParam(required = false) String billEmail,
        @RequestParam(required = false) String faxNumber,@RequestParam(required = false) String recipientName,
        @RequestParam(required = false) String billAddress,@RequestParam(required = false) String postCode,
        @RequestParam(required = false) String remark, @RequestParam(required = true) String acctId,
        @RequestParam(required = true) String custId,@RequestParam(required = true) String groupId,
        @RequestParam(required = false) String provinceCode,@RequestParam(required = false) String eparchyCode,
        @RequestParam(required = false) String bankAcctName,@RequestParam(required = false) String bankAcctNo,
        @RequestParam(required = false) String bankCode,@RequestParam(required = false) String superBankCode,
        @RequestParam(required = false) String limitMode,@RequestParam(required = false) String limitMoney,
        @RequestParam(required = false) String agreementNo,@RequestParam(required = false) String fdContactName,
        @RequestParam(required = false) String fdContactPhone){
        ContextCustDTO conCustDTO = KiteWebContext.getContext().getCust();
        CuccContextCustDTO custDTO = KiteBeanUtils.transform(conCustDTO, CuccContextCustDTO.class);
        return ErrorConsts.SUCCESS.getResult(accountService.modCustAccount(custDTO, payName,accountType,accountCycle,
            payCycle, linkName, linkPhone,linkEmail, linkAddress, postBill, isCenterDirectSign, billType, billCycle,
            billContent, billEmail, faxNumber,recipientName, billAddress, postCode, remark,acctId,custId,groupId,
            provinceCode,eparchyCode, bankAcctName, bankAcctNo, bankCode, superBankCode, limitMode,
            limitMoney, agreementNo, fdContactName, fdContactPhone));
    }

    @ApiOperation(value = "查询账户详情", notes = "查账户详情")
    @GetMapping("queryAccountInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例ID", required = false),
        @ApiImplicitParam(name = "offerInstId", value = "销售品实例ID", required = true),
        @ApiImplicitParam(name = "acctId", value = "账户ID", required = true),
        @ApiImplicitParam(name = "offerObjInstRelId", value = "账户实例ID", required = true),
    })
    public DataResult<List<KiteCuccOfferInstAcct>> queryAccountInfo(@RequestParam(required = false) String sceneInstId,
        @RequestParam(required = true) String offerInstId, @RequestParam(required = true) String acctId,
        @RequestParam(required = true) String offerObjInstRelId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        List<KiteCuccOfferInstAcct> offerInstAccts = Lists.newArrayList();
        //先获取场景里的账户实例
        //        KiteOfferInstAcct offerInstAcct = querySceneInstService.listOfferInstAccts(KiteWebContext.getContext().getCustId(), offerInstId)
        //            .stream().filter(acct -> acctId.equals(acct.getAcctId())).findFirst().orElse(null);
        //非默认账户可以重复添加,所以查看详情的时候按实例的id取
        KiteOfferInstAcct offerInstAcct = querySceneInstService
            .getOfferInstAcct(KiteWebContext.getContext().getCustId(), offerObjInstRelId);
        if (Objects.nonNull(offerInstAcct)) {
            KiteCuccOfferInstAcct cuccOfferInstAcct = new KiteCuccOfferInstAcct();
            KiteBeanUtils.copyProperties(offerInstAcct, cuccOfferInstAcct);
            //部分字段调用接口补充
            CuccContextCustDTO cuccContextCustDTO = (CuccContextCustDTO) KiteWebContext.getContext().getCust();
            String provinceCode = cuccContextCustDTO.getProvinceCode();
            String eparchyCode = cuccContextCustDTO.getEparchyCode();
            PageInfo<QryCustAccountReq> list=new PageInfo<>();
//            //云联网国际账户信息查询
//            String orgProvinceCode=ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
//            if(!KiteStringUtils.isEmpty(orgProvinceCode)&&orgProvinceCode.startsWith("48")||orgProvinceCode.startsWith("49")){
//                list = accountService
//                    .listNationalCustAccountInfo(offerInstAcct.getCustId(), "", "", acctId, "", "", "", provinceCode,
//                        eparchyCode,null, 1, 5);
//            }else {
                list = accountService
                    .listCustAccountInfo(offerInstAcct.getCustId(), "", "", acctId, "", "", "", provinceCode,
                        eparchyCode,null, 1, 5);
//            }

            List<QryCustAccountReq> infResult = list.getList();
            if (KiteListUtils.isNotEmpty(infResult)) {
                QryCustAccountReq req = infResult.get(0);
                cuccOfferInstAcct.setCbssAccountCode(req.getCustAccount().getCbssAccountCode());
                cuccOfferInstAcct.setAccountCycle(req.getCustAccount().getAccountCycle());
                cuccOfferInstAcct.setPayCycle(req.getCustAccount().getPayCycle());
                cuccOfferInstAcct.setAcctName(req.getCustAccount().getPayName());
                cuccOfferInstAcct.setIsCenterDirectSign(req.getCustAccount().getIsCenterDirectSign());
                cuccOfferInstAcct.setStartDate(offerInstAcct.getStartDate());
                cuccOfferInstAcct.setEndDate(offerInstAcct.getEndDate());
                // 开户时间
                if (Objects.nonNull(req.getCustAccount().getOpenDate())) {
                    Long time = req.getCustAccount().getOpenDate().getTime();
                    cuccOfferInstAcct.setOpenDate(DateUtils.formatTime(time));
                }
                // 账户开户员工
                cuccOfferInstAcct.setCreateUserCode(req.getCustAccount().getCreateUserCode());
            }
            offerInstAccts.add(cuccOfferInstAcct);
        }

        return ErrorConsts.SUCCESS.getResult(offerInstAccts);
    }
    @KiteTransactional
    @ApiOperation(value = "提供默认账户查询服务", notes = "提供默认账户查询服务")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例id", required = true),
        @ApiImplicitParam(name = "custId", value = "客户id", required = false)
    })
    @GetMapping("/queryDefaultAcct")
    public DataResult<List<KiteOfferInstAcct>> queryDefaultAcct(String sceneInstId, String custId) {
        String offerInstId = querySceneInstService.getSceneInst(sceneInstId).getRootInstId();
        if (KiteStringUtils.isEmpty(custId)) {
            custId = KiteWebContext.getContext().getCustId();
        }
        List<KiteOfferInstAcct> offerInstAcctRels = querySceneInstService.listOfferInstAccts(custId, offerInstId);
        offerInstAcctRels.stream().filter(KiteOfferInstAcct -> KiteStringUtils.equals("1", KiteOfferInstAcct.getIsDefault())).collect(Collectors.toList());
        operateSceneInstService.putExtParameter(sceneInstId, "transferDefaultAcct", offerInstAcctRels);
        return ErrorConsts.SUCCESS.getResult(offerInstAcctRels);
    }

    @KiteTransactional
    @ApiOperation(value = "保存过户目标账户实例", notes = "保存过户目标账户实例")
    @PostMapping("/addTransferOfferInstAcctRels")
    @ApiImplicitParams({@ApiImplicitParam(name = "acctRels", value = "关联账户（付费关系）", required = true)})
    public DataResult<Map<String, String>> addTransferOfferInstAcctRels(
        @RequestBody(required = true) List<CuccKiteOfferInstAcct> acctRels) {
        DataResult<Map<String, String>> param = new DataResult<Map<String, String>>();

        for (CuccKiteOfferInstAcct acctRel : acctRels) {
            if (KiteStringUtils.isEmpty(acctRel.getCustId())){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("您选择的账户字段付费账目编码为空，请检查后重新选择");
            }
            if (KiteStringUtils.isEmpty(acctRel.getCbssAccountCode())){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("您选择的账户字段CB账户ID为空，请检查后重新选择");
            }
        }
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String custId = KiteWebContext.getContext().getCustId();
//        if (KiteStringUtils.isNotEmpty(kiteSceneInst.getNewCustId())) {
//            custId = kiteSceneInst.getNewCustId();
//        } else {
//            custId = KiteWebContext.getContext().getCustId();
//        }
        String offerInstId = querySceneInstService.getSceneInst(sceneInstId).getRootInstId();

        for(CuccKiteOfferInstAcct cuccKiteOfferInstAcct:acctRels){
            // 过户选择非默认账户时处理报文缺少参数
            cuccKiteOfferInstAcct.setPayLimit(Optional.ofNullable(cuccKiteOfferInstAcct.getPayLimit()).orElse("0"));
            cuccKiteOfferInstAcct.setPayWay(Optional.ofNullable(cuccKiteOfferInstAcct.getPayWay()).orElse("0"));
            cuccKiteOfferInstAcct.setAcctItemId(Optional.ofNullable(cuccKiteOfferInstAcct.getAcctItemId()).orElse("0"));
        }

        /**校验新增的付费关系-start*/
            RuleCommonParam ruleCommonParam = RuleParamUtils.getRuleParam();
            Map map = new HashMap();
            List acctRelList = new ArrayList();
            acctRels.stream().forEach(acctRel ->{
                Map acctRelMap = KiteMapUtils.beanToMap(acctRel);
                acctRelList.add(acctRelMap);
            });
            map.put("prodInstAcctRels", acctRelList);
            ruleCommonParam.setParams(map);
            KiteRuleResponse response = checkService.onAddProdInstAcctRule(sceneInstId, "", "","", ruleCommonParam);
            RuleResponseUtils.cheackRuleResp(response);
        /**校验新增的付费关系-end*/

        //获取已有的付费关系
        List<KiteOfferInstAcct> offerInstAcctRels = querySceneInstService.listOfferInstAccts(custId, offerInstId);
        if (KiteListUtils.isNotEmpty(offerInstAcctRels)) {
            for (KiteOfferInstAcct offerInstAcct : offerInstAcctRels) {
                //循环删除
                operateSceneInstService.deleteOfferInstAcct(sceneInstId, offerInstAcct.getOfferObjInstRelId());
            }
        }

        for (CuccKiteOfferInstAcct offerInstAcct : acctRels) {
            if (KiteStringUtils.equals(offerInstAcct.getActionType().name(), ActionType.D.name())) {
                operateSceneInstService.deleteOfferInstAcct(sceneInstId, offerInstAcct.getOfferObjInstRelId());
            } else {
                offerInstAcct.setInstType(InstType.OFFER_INST_ACCT);
                KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, offerInstId);
                if (KiteObjectUtils.isEmpty(offerInst)) {
                    ErrorConsts.OFFER_INST_NOT_EXIST.throwOut(offerInstId, custId);
                }
                // 没有账户明细关系，明细ID传销售品id
                String offerId = Optional.ofNullable(OfferCache.get(offerInst.getOfferId())).map(Offer::getOfferId)
                    .orElse("");
                operateSceneInstService
                    .addOfferInstAcct(sceneInstId, offerInstAcct, offerInstId, RelType.OFFER_OBJ_REL_TYPE_170000,
                        ActionType.A, KeyConsts.OFFER_ACCOUNT_ROLE, offerId);
            }
        }
        param.setResultCode("0");
        param.setResultMsg("SUCCESS");
        return param;
    }

    @ApiOperation(value = "查询所有付费关系实例", notes = "查询所有付费关系实例")
    @GetMapping("listAllOfferInstAcctRels")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例ID", required = false),
        @ApiImplicitParam(name = "offerInstId", value = "销售品实例ID", required = false)
    })
    public DataResult<List<KiteOfferInstAcctVO>> listAllOfferInstAcctRels(
        @RequestParam(required = false) String sceneInstId, @RequestParam(required = false) String offerInstId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        List<CuccKiteOfferInstAcct> offerInstAccts = Lists.newArrayList();
        List<KiteOfferInst> mainOfferInsts = this.querySceneInstService.listMainOfferInsts(sceneInstId);
        List<KiteInstChange> instChangeList = querySceneInstService.listInstChanges(sceneInstId, InstType.OFFER_INST_ACCT);
        List<KiteOfferInst> giftOfferInsts = querySceneInstService.listGiftOfferInsts(sceneInstId);
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        InstType instType = sceneInst.getRootInstType();
        if (KiteListUtils.isNotEmpty(giftOfferInsts)) {
            KiteOfferInst offerInst = giftOfferInsts.get(0);
            offerInstAccts.addAll(KiteBeanUtils.copyPropsForList(operateOfferInstAcctRelService
                .listOfferInstAccts(KiteWebContext.getContext().getCustId(), offerInst.getOfferInstId()), CuccKiteOfferInstAcct.class));
        }
        else {
            if (!KiteListUtils.isEmpty(mainOfferInsts)) {
                for (KiteOfferInst offerInst : mainOfferInsts) {
                    offerInstAccts.addAll(KiteBeanUtils.copyPropsForList(operateOfferInstAcctRelService
                        .listOfferInstAccts(KiteWebContext.getContext().getCustId(), offerInst.getOfferInstId()), CuccKiteOfferInstAcct.class));
                }
            }
        }
        offerInstAccts.stream().forEach(offerInstAcct ->{
            if (KiteStringUtils.isEqual(ActionType.M.name(), offerInstAcct.getActionType().name())) {
                KiteInstChange kiteInstChange = instChangeList.stream()
                    .filter(change -> offerInstAcct.getInstId().equals(change.getSubInstId()))
                    .findFirst().orElse(null);
                ActionType actionType = Objects.nonNull(kiteInstChange) ? kiteInstChange.getActionType() : offerInstAcct.getActionType();
                offerInstAcct.setActionType(actionType);
            }
        });
        List<KiteOfferInstAcctVO> copy = KiteBeanUtils.copyPropsForList(offerInstAccts, KiteOfferInstAcctVO.class);
        for (KiteInstChange instChange : instChangeList) {
            KiteOfferInst offerInst = new KiteOfferInst();
            if (Objects.equals(InstType.GIFT_OFFER_INST, instType)) {
                //如果是融合场景
                offerInst = querySceneInstService.getOfferInst(sceneInst.getCustId(), sceneInst.getRootInstId());
            } else {
                offerInst = mainOfferInsts.stream().filter(mainOffer -> KiteStringUtils.equals(instChange.getInstId(), mainOffer.getOfferInstId())).findFirst().orElse(null);
            }
            if (Objects.nonNull(offerInst) && KiteStringUtils.isEqual(instChange.getNewValue(),ActionType.D.name())
                && !KiteStringUtils.isEqual(instChange.getOldValue(),ActionType.A.name())) {

                List<KiteOfferInstAcct> delOfferInstAccts = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.OFFER_INST_ACCT));
             // 删除的付费关系
                delOfferInstAccts.forEach((acctRel) -> {
                    if (KiteStringUtils.isEqual(ActionType.D.name(), acctRel.getActionType().name())
                        && KiteStringUtils.isEqual(instChange.getSubInstId(), acctRel.getInstId())) {
                        if (isPayRelation(copy, acctRel)) {
                            copy.add(KiteBeanUtils.transform(acctRel, KiteOfferInstAcctVO.class));
                        }
                    }

                });
            }
        }
        if (KiteListUtils.isNotEmpty(copy)) {
            KiteAttr accNumAttr = querySceneInstService.getCommonAttr(sceneInstId, "business_number");
            String accNum = accNumAttr != null ? accNumAttr.getValue() : "";
            for (KiteOfferInstAcctVO vo : copy) {
                if (vo == null) {
                    continue;
                }
                vo.setAccNum(accNum);
            }
        }
        return ErrorConsts.SUCCESS.getResult(copy);
    }

    private boolean isPayRelation(List<KiteOfferInstAcctVO> payRelations, KiteOfferInstAcct delPayRelation) {
        String accountInstId = delPayRelation.getAcctId();
        String iSdefault = delPayRelation.getIsDefault();
        for (KiteOfferInstAcctVO payRelation : payRelations) {
            if (KiteStringUtils.isEqual(payRelation.getAcctId(), accountInstId)
                && KiteObjectUtils.nullSafeEquals(payRelation.getIsDefault(), iSdefault)) {
                payRelation.setActionType(ActionType.K);
                return false;
            }
        }
        return true;
    }

    @KiteTransactional
    @ApiOperation(value = "提供默认账户查询服务(质检/重提)", notes = "提供默认账户查询服务(质检/重提)")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例id", required = true)
    })
    @GetMapping("/queryDefaultAcctResubmit")
    public DataResult<List<TargetAccountInfoVO>> queryDefaultAcctResubmit(String sceneInstId) {
        List<TargetAccountInfoVO> targetAccountInfoList = new ArrayList<>();

        String offerInstId = querySceneInstService.getSceneInst(sceneInstId).getRootInstId();
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String taskCode = querySceneInstService.getExtParameterValue(sceneInstId, "taskCode");
        // 判断当前流程是过户质检/重提 才处理
        if (KiteStringUtils.equalsAny(taskCode, "OrderResubmit", "OrderSignedCheckSHZWY", "OrderResubmitZWY", "OrderResubmitXSWLW")
            && KiteStringUtils.equals(ServiceOfferConsts.SERVICE_OFFER_TRANSFER, sceneInst.getServiceOfferId())) {
            List<KiteOfferInstAcct> allAcctRels = querySceneInstService.listOfferInstAccts(sceneInst.getCustId(), offerInstId);
            allAcctRels = allAcctRels.stream().filter(allAcctRel -> ActionType.K.equals(allAcctRel.getActionType())).collect(Collectors.toList());
           // 过滤默认账户后 转换成前台展示字段的格式
            for (KiteOfferInstAcct allAcctRel : allAcctRels) {
                CuccKiteOfferInstAcct cuccAllAcctRel = (CuccKiteOfferInstAcct) allAcctRel;
                TargetAccountInfoVO targetAccountInfoVO = new TargetAccountInfoVO();
                targetAccountInfoVO.setCbssAccountCode(allAcctRel.getCbssAccountCode());
                targetAccountInfoVO.setContractId(cuccAllAcctRel.getContractId());
                targetAccountInfoVO.setPayName(cuccAllAcctRel.getAcctName());
                targetAccountInfoVO.setPayModeCode(cuccAllAcctRel.getPayModeCode());
                targetAccountInfoVO.setProvinceCode(cuccAllAcctRel.getProvinceCode());
                targetAccountInfoVO.setEparchyCode(cuccAllAcctRel.getEparchyCode());
                targetAccountInfoVO.setAcctId(cuccAllAcctRel.getAcctId());
                targetAccountInfoVO.setAccountLocation(LocalAttrHelper.getRegionName(cuccAllAcctRel.getProvinceCode())
                    + "-" + LocalAttrHelper.getRegionName(cuccAllAcctRel.getEparchyCode()));
                if (KiteStringUtils.isEmpty(cuccAllAcctRel.getOpenDateFormat())) {
                    targetAccountInfoVO.setOpenDateFormat("");
                } else {
                    targetAccountInfoVO.setOpenDateFormat(cuccAllAcctRel.getOpenDateFormat());
                }
                if (KiteStringUtils.isEmpty(cuccAllAcctRel.getProvinceAcctId())) {
                    targetAccountInfoVO.setProvinceAccountId("");
                } else {
                    targetAccountInfoVO.setProvinceAccountId(cuccAllAcctRel.getProvinceAcctId());
                }
                targetAccountInfoList.add(targetAccountInfoVO);
            }
            return ErrorConsts.SUCCESS.getResult(targetAccountInfoList);
        }
        return ErrorConsts.SUCCESS.getResult(targetAccountInfoList);
    }
}
